#### Script to do multiple treeMI imputations for the ready-mix boxes industry
### and export the imputed dataset

#### input files:
####	boxes_gooddata.csv
####
#### output files:
####	boxes_imputes.csv
####    boxes_predicted.csv

require(tree,lib.loc="/tree")

#### read in the "good" dataset, in which we have replaced the Census Bureau imputes/edits with missing values
boxes_gooddata<-read.csv("boxes_gooddata02.csv",header=TRUE)

### Create completed datasets using treeMI:


boxes_imputes<-treeMI(boxes_gooddata,ITER=5,c(0,0,0,0,0,0,0,0,0,0,0,1,0),starter=TRUE,PPDdraw = TRUE, minCut = 5,minDev  = 0.000001, startCut = 5, startDev = 0.000001) 

boxes_imputes$impSet$impsetnum <- 1
boxes_imputes$PPDsample$impsetnum <- 1

### For the first imputed dataset, create a new file
write.table(boxes_imputes$impSet,file="boxes_imputes02.csv",append=FALSE,sep=",") 
write.table(boxes_imputes$PPDsample,file="boxes_predicted02.csv",append=FALSE,sep=",") 

for (j in 2:500) {

boxes_imputes<-treeMI(boxes_gooddata,ITER=5,c(0,0,0,0,0,0,0,0,0,0,0,1,0),starter=TRUE,PPDdraw = TRUE, minCut = 5,minDev  = 0.000001, startCut = 5, startDev = 0.000001) 

boxes_imputes$impSet$impsetnum <- j
boxes_imputes$PPDsample$impsetnum <- j

### Append the subsequent imputed datasets to the file created for the first dataset

write.table(boxes_imputes$impSet,file="boxes_imputes02.csv",append=TRUE,sep=",",col.names=FALSE) 
write.table(boxes_imputes$PPDsample,file="boxes_predicted02.csv",append=TRUE,sep=",",col.names=FALSE) 

}


